package com.asen.libcommon.widget

import android.app.Activity
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.core.content.ContextCompat
import com.asen.libcommon.R
import com.asen.libcommon.base.iface.BaseJSCall
import com.asen.libcommon.databinding.ViewBaseX5WebBinding
import com.orhanobut.logger.Logger
import com.tencent.smtt.sdk.ValueCallback
import com.tencent.smtt.sdk.WebStorage
import com.ycbjie.webviewlib.InterWebListener
import com.ycbjie.webviewlib.WebProgress
import com.ycbjie.webviewlib.X5WebUtils
import com.ycbjie.webviewlib.X5WebView

/**
 * @date   : 2021/4/21
 * @author : asenLiang
 * @e-mail : liangAisiSen@163.com
 * @desc   : 封装 x5WebView
 */
class BaseX5WebView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    // todo：静态定义
    companion object {
        // todo：js 调用：window. + JS_ANDROID_KEY. + 安卓方法(参数/null)
        const val JS_ANDROID_KEY: String = "iTop"  // 常量
        const val userAgent: String = "itopClient" // 常量
    }

    private var x5WebView: X5WebView? = null
    private var mWebProgress: WebProgress? = null

    private val mBinding: ViewBaseX5WebBinding

    init {
        inflate(context, R.layout.view_base_x5_web, this)
        mBinding = ViewBaseX5WebBinding.bind(this)
        x5WebView = findViewById(R.id.x5WebView)
        mWebProgress = findViewById(R.id.mWebProgress)

        mWebProgress?.apply {
            setColor(
                ContextCompat.getColor(context, R.color.white_FFFFFF),
                ContextCompat.getColor(context, R.color.color_blue_ff)
            )
            show()
        }

        x5WebView?.apply {
            x5WebChromeClient.setWebListener(mInterWebListener)
            x5WebViewClient.setWebListener(mInterWebListener)
            //设置UA
            settings.userAgentString = settings.userAgentString + userAgent
//            // JSBaseInterface与js交互类  android 用于回调 js 和 android 方法的 key 值
//            addJavascriptInterface(null, JS_ANDROID_KEY) // 初始化 webView
        }

    }

    private val mInterWebListener: InterWebListener = object : InterWebListener {
        override fun showTitle(title: String?) {
            onCallShowTitle?.invoke(title)
        }

        override fun hindProgressBar() {
            mWebProgress?.hide()
        }

        override fun startProgress(newProgress: Int) {
            mWebProgress?.setWebProgress(newProgress)
        }

        override fun showErrorView(type: Int) {

            when (type) {
                //没有网络
                X5WebUtils.ErrorMode.NO_NET -> {
                    Logger.d("没有网络---->:$")
                }
                //404，网页无法打开
                X5WebUtils.ErrorMode.STATE_404 -> {
                    Logger.d("网页无法打开---->:$")
                }
                //onReceivedError，请求网络出现error
                X5WebUtils.ErrorMode.RECEIVED_ERROR -> {
                    Logger.d("请求网络出现error---->:$")
                }
                //在加载资源时通知主机应用程序发生SSL错误
                X5WebUtils.ErrorMode.SSL_ERROR -> {
                    Logger.d("在加载资源时通知主机应用程序发生SSL错误---->:$")
                }
                else -> {
                }
            }

        }

    }


    private var onCallShowTitle: ((title: String?) -> Unit?)? = null


    fun <T : BaseJSCall> setCallBack(onShowTitle: ((title: String?) -> Unit?)? = null, t: T?) {
        onCallShowTitle = onShowTitle
        // JSBaseInterface与js交互类  android 用于回调 js 和 android 方法的 key 值
        x5WebView?.addJavascriptInterface(t, JS_ANDROID_KEY) // 初始化 webView
    }

    fun goBack(activity: Activity? = null, call: (() -> Unit?)? = null): Boolean {
        x5WebView?.apply {
            call?.invoke()
            if (pageCanGoBack()) {
                //退出网页
                return pageGoBack()
            } else { // 关闭监听
                if (call == null)
                    when {

                        Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> {
                            activity?.finishAfterTransition()
                        }
                        else -> {
                            activity?.finish()
                        }
                    }
            }
        }
        return false
    }


    /**
     * @param clearCache 是否刪除所有緩存
     */
    fun destroy(clearCache: Boolean = true) {
        try {
            x5WebView?.apply {
                //                var parent: ViewGroup? = x5WebView.parent as ViewGroup
//                parent?.removeView(x5WebView)
//                x5WebView.removeAllViews();
                loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
                stopLoading();
                x5WebChromeClient.setWebListener(null)
                x5WebViewClient.setWebListener(null)
                webChromeClient = null;
                webViewClient = null;
                if (clearCache) {
                    // 删除缓存
                    clearCache(true)
//                this.deleteDatabase("webview.db");
//                this.deleteDatabase("webviewCache.db");
                    // 清空Cookie
//                CookieSyncManager.createInstance(this);
//                CookieManager.getInstance().removeAllCookie();
//                CookieManager.getInstance().removeSessionCookie();
//                CookieManager.getInstance().removeSessionCookies(null)
//                CookieManager.getInstance().removeAllCookies(null);
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
//                    CookieManager.getInstance().flush();
//                }else{
//                    CookieSyncManager.getInstance().sync();
//                }
//                CookieSyncManager.getInstance().startSync();
                    // 清空H5保存在本地的所有内容；
                    WebStorage.getInstance().deleteAllData() // 清空H5保存在本地的所有内容；webView的所有数据都会删除
                }
                destroy()
            }
        } catch (e: Exception) {
            Logger.d(e.message)
        }
    }

    /**
     * android触发js方法或往js添加新元素
     */
    fun addJsAction(actionName: String, callback: ValueCallback<String>?) {
        x5WebView?.evaluateJavascript(actionName, callback)
    }

    fun loadUrl(url: String? = "") {
        x5WebView?.loadUrl(url)
    }

    fun url(): String {
        return mBinding.x5WebView.url ?: ""
    }

//    override fun onDetachedFromWindow() {
//        destroy()
//        super.onDetachedFromWindow()
//    }


}